<template>
  <div class="page-cart">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />

    <div class="body">
      <van-swipe-cell v-for="item in store.list" :key="item.cartid">
        <template #default>
          <MyCard
            show-checkbox
            :checked="item.flag"
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
            @change="onChange(item.cartid, $event)"
            :num="item.num"
            @update:num="onChangeNum(item.cartid, $event)"
          />
        </template>

        <template #right>
          <van-button
            type="danger"
            square
            class="delete-button"
            text="删除"
            @click="onDeleteCart(item.cartid)"
          />
        </template>
      </van-swipe-cell>
    </div>

    <div class="footer">
      <van-submit-bar :price="store.total" button-text="提交订单">
        <van-checkbox :model-value="store.isAll" @update:model-value="fn1"
          >全选</van-checkbox
        >
      </van-submit-bar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch } from "vue";
//引入my-card
import MyCard from "@/components/my-card.vue";

import { useCartStore } from "@/stores/cart";
import { useUseStore } from "@/stores/user";
import { updateCheckedAll } from "@/api/cart";

const store = useCartStore();
const userStore = useUseStore();

onMounted(() => {
  //调用action获取列表数据
  store.getList();
});

//勾选按钮状态处理函数
const onChange = (cartid: string, isChecked: boolean) => {
  // console.log('onChange',isChecked)
  //可以省掉onChange方法,直接调用下面这个仓库方法也行
  store.setChecked(cartid, isChecked);
};

//数量操作
const onChangeNum = (cartid: string, num: number) => {
  // 调用store.setNum(cartid,isChecked)
  //可以省掉onChangeNum方法,直接调用下面这个仓库方法也行
  store.setNum(cartid, num);
};

//全选
const fn1 = (isChecked: boolean) => {
  // console.log("fn1", isChecked);
  //判断是否要勾选上
  if (isChecked) {
    //全选
    store.list = store.list.map((item) => ({
      ...item,
      flag: true,
    }));
  } else {
    //取消全选
    store.list = store.list.map((item) => ({
      ...item,
      flag: false,
    }));
  }
  //调用接口更新数据库信息
  updateCheckedAll(userStore.userid, isChecked);
};

//删除单个商品
const onDeleteCart = async(cartid: string) => {
  // console.log("cartid",cartid)
  //调用接口
  await store.deleteCart(cartid);
  //删除成功后,更新商品列表
  store.getList();
};
</script>

<style lang="scss" scoped>
.delete-button {
  height: 100%;
}

.van-swipe-cell:not(:first-child) {
  margin-top: 20px;
}

.van-submit-bar {
  position: static;
}

.page-cart {
  height: 100%;
  display: flex;
  flex-direction: column;
  .body {
    flex: 1;
    overflow-y: auto;
  }
}
</style>
